import classNames from 'classnames';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import React, { useEffect, useMemo, useRef } from 'react';
import TabContext from './TabContext';
import TabNavList from './TabNavList';
import TabPanelList from './TabPanelList';
import type { TabsProps } from './interface';

const YmTabs: React.FC<TabsProps> = (props) => {
  const {
    id,
    prefixCls = 'ym-tabs',
    rootClassName, //div.ym-tabs对应的className
    items,
    activeKey,
    defaultActiveKey,
    tabBarGutter = 32,
    tabBarStyle,
    tabBarListStyle,
    tabPosition = 'top',
    destroyInactiveTabPane,
    onChange,
    onTabClick,
    onTabScroll,
    noneedTabPane = false,
    animated,
  } = props;
  const uuidRef = useRef<number>(0);

  const tabs = useMemo(
    () =>
      (items || []).filter(
        (item) => item && typeof item === 'object' && 'key' in item,
      ),
    [items],
  );

  // ===================== Accessibility ====================
  const [mergedId, setMergedId] = useMergedState(null, {
    value: id,
  });

  // Async generate id to avoid ssr mapping failed
  useEffect(() => {
    if (!id) {
      setMergedId(`rc-tabs-${uuidRef.current}`);
      uuidRef.current += 1;
    }
  }, []);

  // ====================== Active Key (受控与非受控)======================
  const [mergedActiveKey, setMergedActiveKey] = useMergedState<string>(
    () => tabs[0]?.key,
    {
      value: activeKey,
      defaultValue: defaultActiveKey,
    },
  );

  // ======================== Events ========================
  function onInternalTabClick(
    key: string,
    e: React.MouseEvent | React.KeyboardEvent,
  ) {
    // console.log('--Tab--onInternalTabClick--key--:', key);
    onTabClick?.(key, e);
    const isActiveChanged = key !== mergedActiveKey;
    setMergedActiveKey(key);
    if (isActiveChanged) {
      onChange?.(key);
    }
  }

  const sharedProps = {
    id: mergedId!,
    activeKey: mergedActiveKey,
    animated: animated ?? { inkBar: true, tabPane: false },
    tabPosition,
  };

  const tabNavBarProps = {
    ...sharedProps,
    tabBarGutter,
    style: tabBarStyle,
    tabBarListStyle,
    onTabClick: onInternalTabClick,
    onTabScroll,
  };

  return (
    <TabContext.Provider value={{ tabs, prefixCls }}>
      <div
        className={classNames(
          prefixCls,
          `${prefixCls}-${tabPosition}`,
          rootClassName,
        )}
      >
        <TabNavList {...tabNavBarProps} />
        {!noneedTabPane && (
          <TabPanelList
            {...sharedProps}
            destroyInactiveTabPane={destroyInactiveTabPane}
          />
        )}
      </div>
    </TabContext.Provider>
  );
};

export default YmTabs;
